multer
✒️ 2025-05-26 14:17 내용 수정
Node.js 교과서 개정 3판 내용 정리
- 이미지, 동영상, 파일 등 여러 파일을 multipart 형식으로 업로드할 때 사용한다.
- multipart : enctype="multipart/form-data"인 form을 통해 업로드 되는 데이터 형식
- JSP의 파일 업로드와 model 2, Spring의 파일 업로드 설정하기에도 적용했었다.
- MIME 타입 참고.
- multer를 사용하려면 VSC 터미널에서 먼저 다운 받아야 한다.
npm i multer
- server.js에서 multer 설정을 작성한다.
- 파일 업로드 설정을 하려면 서버에 파일을 저장할 폴더가 반드시 필요하다.
- 설정이 끝나면 upload 변수가 생성되며, 업로드할 파일 개수에 따라 single이나 array 미들웨어를 사용한다.
| 옵션 | 세부설정 | 설명 |
|---|---|---|
| storage | 파일 저장 위치와 이름 설정 | |
| destination | 파일 저장 위치 설정 | |
| filename | 파일 이름 설정 | |
| limit | 업로드 제한 설정 |
const multer = require('multer');
const uuid4 = require('uuid4'); // Universally Unique Identifier
const upload = multer({
storage: multer.diskStorage({ // 저장할 옵션 설정
filename(req, file, done) { // 저장 파일명 지정
const randomID = uuid4();
const ext = path.extname(file.originalname);
const filename = randomID + ext; // 중복된 이름 방지를 위한 이름 설정
done(null, filename ); // 첫번째 인수는 에러, 두번째 인수는 파일 이름
},
destination(req, file, done) { // 저장위치
// 첫번째 인수는 에러, 두번째 인수는 저장 경로
done(null, path.join(__dirname, "/public/images/profile"));
},
limits : {fileSize : 1024 * 1024} // 크기 제한
}),
});
// 파일을 1개만 업로드 할 때 single 미들웨어 설정
const singleUpload = upload.single('myProfile');
// 파일을 여러 개 업로드 할 때 array 미들웨어 설정
const multipleUpload = upload.array('profiles');
// 미들웨어 사용
app.use(uploadMiddleware);
// 파일을 업로드할 페이지
app.get('/upload', (req, res)=>{
res.render('img-upload.ejs')
});
// 파일 업로드(1개)
app.post('/upload', singleUpload, (req, res)=>{
console.log(req.file);
res.status(200).send('uploaded');
})
// 파일 업로드(여러개)
app.post('/upload', multipleUpload, (req, res)=>{
console.log(req.files);
res.status(200).send('uploaded');
})
- 파일을 업로드할 페이지에는 form 태그에
enctype=multipart/form-data속성을 추가한다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>이미지 업로드 테스트</h2>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="myProfile" />
<!-- 파일을 여러 개 업로드할 때는 multiple attribute를 추가한다 -->
<!-- <input type="file" name="myProfile" multiple > -->
<button type="submit">Upload</button>
</form>
</body>
</html>